package com.quanshi.shopping_cart_service.service;

import cn.hutool.core.collection.CollUtil;
import com.quanshi.shopping_common.constant.RedisKey;
import com.quanshi.shopping_common.entity.CartGoods;
import com.quanshi.shopping_common.service.ICartService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;


@DubboService
public class CartServiceImpl implements ICartService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addCart(Long userId, CartGoods cartGoods) {
        //获取购物车商品数据
        List<CartGoods> cartList = findCartList(userId);

        for (CartGoods goods : cartList) {
            //如果购物车之前有这个商品，只需要添加一次数量即可
            if (cartGoods.getGoodId().equals(goods.getGoodId())) {
                goods.setNum(goods.getNum() + cartGoods.getNum());
                redisTemplate.boundHashOps(RedisKey.CART_LIST).put(userId,cartList);
                return;
            }
        }
        cartList.add(cartGoods);
        //重新设置购物车
        //获取操作Hash类型的对象
        redisTemplate.boundHashOps(RedisKey.CART_LIST).put(userId,cartList);

    }

    @Override
    public void handleCart(Long userId, Long goodId, Integer num) {

        //获取购物车数据
        List<CartGoods> cartList = findCartList(userId);
        for (CartGoods cartGoods : cartList) {
            if (goodId.equals(cartGoods.getGoodId())) {
                cartGoods.setNum(num);
                break;
            }
        }
        //重设置数据到购物车
        //获取操作Hash类型的对象
        redisTemplate.boundHashOps(RedisKey.CART_LIST).put(userId,cartList);
    }

    @Override
    public void deleteCartOption(Long userId, Long goodId) {
        //获取购物车数据
        List<CartGoods> cartList = findCartList(userId);

        //过滤不需要删除的数据
        cartList = cartList.stream().filter(cartGoods -> !goodId.equals(cartGoods.getGoodId())).toList();

        //获取操作Hash类型的对象
        //判断当前用户购物车是否删完
        if (CollUtil.isNotEmpty(cartList)) {
            //重设置数据到购物车
            redisTemplate.boundHashOps(RedisKey.CART_LIST).put(userId,cartList);
        } else {
            //删除完毕，直接删除当前用户在购物车中的hash的key
            redisTemplate.boundHashOps(RedisKey.CART_LIST).delete(userId);
        }

    }

    @Override
    public List<CartGoods> findCartList(Long userId) {
        Object cartList = redisTemplate.boundHashOps(RedisKey.CART_LIST).get(userId);
        if (Objects.nonNull(cartList)) {
            return (List<CartGoods>) cartList;
        }
        return new ArrayList<>();
    }

    @Override
    public void refreshCartGoods(CartGoods cartGoods) {

    }

    @Override
    public void deleteCartGoods(Long goodId) {

    }
}
